//
//  HWTakeALookCommentDetailController.swift
//  PlayWithProject
//
//  Created by 王昌健 on 2021/8/5.
//

import UIKit
import IQKeyboardManagerSwift
class HWTakeALookCommentDetailController: HWBaseViewController {
    /// 上级传过来的一级评论模型
    var superCommentModel:HWTakeALookCommentModel?
    var ppidModel:HWTakeALookCommentModel?
    var donttai_id = ""
    
    var tableView:UITableView!
    
    let tableViewProtocol = HWTakeALookCommentDetailProtocol()
    let httpManager = HWGameCircleHttpManager()
    let mutDataArr = NSMutableArray()
    var keyboardView:HWCommentKeyboardView!
    var tempBgView:UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        addRefresh()
        
        loadData()
        
        addAction()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
    }
}

extension HWTakeALookCommentDetailController{
    private func initUI() -> Void {
        navigationView.titleLabel.text = "\(superCommentModel?.data_num ?? 0)" + "条评论"
        navigationView.backButton.setImage(UIImage(named: "fanhui"), for: .normal)
        
        tableViewProtocol.superModel = superCommentModel
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = UIColor.colorWithHexString(hexString: "F2F2F2")
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        view.addSubview(tableView)
        
        tempBgView = UIView.init()
        tempBgView.backgroundColor = UIColor.clear
        tempBgView.isHidden = true
        view.addSubview(tempBgView)
        
        keyboardView = HWCommentKeyboardView()
        view.addSubview(keyboardView)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrameNotify(_:)), name:UIResponder.keyboardWillChangeFrameNotification, object: nil)
        
        let tapBg = UITapGestureRecognizer.init(target: self, action: #selector(closeKeyboard))
        tempBgView.addGestureRecognizer(tapBg)
    }
    
    private func initFrame() -> Void {
        tableView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(navigationView.snp.bottom)
            make.bottom.equalTo(-88)
        }
        
        tempBgView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(0)
            
        }
        
        keyboardView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            //            make.bottom.equalTo(-34)
            if #available(iOS 11, *){
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            }else{
                make.bottom.equalTo(0)
            }
        }
    }
}
extension HWTakeALookCommentDetailController{
    func addRefresh() -> () {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        httpManager.getTakeALookCommentDetailListFooter(id: superCommentModel?.id ?? "") { models in
            if (models.count > 0){
                self.mutDataArr.addObjects(from: models)
            }
            self.navigationView.titleLabel.text = "\(self.mutDataArr.count)" + "条评论"
            self.tableViewProtocol.models = self.mutDataArr as? [HWTakeALookCommentModel]
            self.tableView.reloadData()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        } failure: { error in
            if error == "没有更多了"{
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }else{
                self.tableView.mj_footer?.endRefreshing()
            }
            
        }
    }
    
    func loadData() -> Void {
        
        httpManager.getTakeALookCommentDetailList(id: superCommentModel?.id ?? "") { models in
            
            //            if (homeModel.data != nil){
            //            self.mutDataArr.removeAllObjects()
            self.tableViewProtocol.models = models
            if (models.count > 0){
                self.mutDataArr.removeAllObjects()
                self.mutDataArr.addObjects(from: models)
            }
            self.navigationView.titleLabel.text = "\(self.mutDataArr.count)" + "条评论"
            self.tableView.reloadData()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
    
}
extension HWTakeALookCommentDetailController{
    @objc func keyboardWillChangeFrameNotify(_ notify:NSNotification) -> Void {
        let duration = notify.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let keyboardFrame = notify.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let transformY = keyboardFrame.origin.y - self.view.frame.size.height;
        UIView.animate(withDuration: duration) {
            
            if transformY == 0.0 {
                self.tempBgView.isHidden = true
                self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
                self.keyboardView.textField.placeholder = "请输入评论内容..."
                self.keyboardView.textField.text = ""
                self.ppidModel = nil
            }else{
                self.tempBgView.isHidden = false
                //                self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY + 34)
                if screenHeight < 812 {
                    self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
                    
                }else {
                    self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY + 34)
                }
            }
            
        }
    }
    
    @objc func closeKeyboard() -> Void {
        view.endEditing(true)
    }
    
    func addAction() -> Void {
        keyboardView.sendText = {
            if HWLocallyStoredData.getLoginUserID().count>0{
                if $0.count > 0 {
                    if self.superCommentModel?.id == self.ppidModel?.id {
                        self.ppidModel = nil
                    }
                    self.httpManager.setTakeALookReplyComment(dongtai_id: self.donttai_id, pid: self.superCommentModel?.id ?? "", ppid: self.ppidModel?.id ?? "", content: $0) { message in
                        //                        self.view.showHUD(title: "评论成功，审核通过后展示")
                        self.loadData()
                        self.view.endEditing(true)
                        
                    } failure: { error in
                        self.view.showHUD(title: error)
                    }
                    
                }else{
                    self.view.showHUD(title: "内容不能为空")
                }
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
            
        }
        
        tableViewProtocol.didSelectRow = {
            self.ppidModel = $0
            self.keyboardView.textField.placeholder = "回复：" + $0.pet_name
            self.keyboardView.textField.becomeFirstResponder()
        }
        
        tableViewProtocol.zanButtonClick = {
            type,id in
            if HWLocallyStoredData.getLoginUserID().count>0{
                self.httpManager.setTakeALookZan(type: type, id: id) { message in
                    //                self.is_look = "1"
                    self.loadData()
                    
                    
                } failure: { error in
                    
                }
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
        }
        
    }
}
extension HWTakeALookCommentDetailController{
    
}
